﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Com.JunCaiSoft.API;
using Com.JunCaiSoft.AutoMapper;
using Com.JunCaiSoft.Common.AssistClass;
using Com.JunCaiSoft.Permission.Common;
using Com.JunCaiSoft.Permission.Entity;
using Com.JunCaiSoft.Permission.IDao;
using Com.JunCaiSoft.Permission.Model;
using IdentityServer4.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace Com.JunCaiSoft.Permission.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [AllowAnonymous]
    public class AuthorizeController : ControllerBase
    {
        /// <summary>
        /// 用户服务类
        /// </summary>
        private readonly IUserDao UserDao;
        /// <summary>
        /// 角色服务类
        /// </summary>
        private readonly IRoleDao RoleDao;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userDao"></param>
        /// <param name="roleDao"></param>
        public AuthorizeController(IUserDao userDao, IRoleDao roleDao)
        {
            UserDao = userDao;
            RoleDao = roleDao;
        }

        [HttpPost]
        public virtual async Task<ActionResult> SignInAsync(LoginUserInfo loginViewModel)
        {
            //if(loginUser.username == "xsjssa" && loginUser.password == "xsjs12345+")
            //{

            //}
            User loginUser;

            loginUser = await UserDao.GetAsync(x => x.UserName == loginViewModel.username);

            if(loginUser == null)
            {
                throw new Exception("用户名错误！");
            }

            var SignInResult = HashPassword.MD5Password(loginViewModel.password) ==  loginUser.Password;

            if (SignInResult)
            {

                var one = loginUser.MapTo<UserInfo>();
                
                one.AccessToken = TokenExtension.GetAccessToken(loginUser);

                one.Begins = DateTime.Now;

                one.Expires = DateTime.Now.AddDays(1);

                var AuthorizeList = APIConfig.GetAuthorizes();

                foreach (var item in AuthorizeList)
                {
                    item.@checked = true;
                    if (item.children != null)
                    {
                        foreach (var inneritem in item.children)
                        {
                            inneritem.@checked = true;
                        }
                    }
                }

                one.Authorizes = JsonConvert.SerializeObject(AuthorizeList);

                return await Task.Run(() => Content(JsonConvert.SerializeObject(one)));

            }
            else
            {
                throw new Exception("密码错误！");
            }
        }
        /// <summary>
        /// 系统登录状态监测
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public virtual async Task<ActionResult> LoginStatus()
        {
            return await Task.Run(() => Content(JsonConvert.SerializeObject(1)));
        }
        /// <summary>
        /// 系统登出
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public virtual async Task<ActionResult> SignOutAsync()
        {
            return await Task.Run(() => Content(JsonConvert.SerializeObject(1)));
        }
        /// <summary>
        /// 登录状态查询
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public virtual async Task<ActionResult> SignStatusAsync()
        {
            return await Task.Run(() => Content(JsonConvert.SerializeObject(1)));
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="DeCodePassword"></param>
        /// <param name="UserId"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public virtual async Task<ActionResult> ChangePassword(String DeCodePassword,Guid UserId)
        {
            try
            {
                await UserDao.dbContext.Database.BeginTransactionAsync();

                return await Task.Run(() => Content(JsonConvert.SerializeObject("")));
            }
            catch(Exception e)
            {
                await UserDao.dbContext.Database.RollbackTransactionAsync();
                throw e;
            }
            finally
            {
                await UserDao.dbContext.Database.CommitTransactionAsync();
            }
            
        } 
    }
}
